<template>
  <el-dialog :visible="dialogVisible"
             :title="title"
             :width="isAdmin ? '531px' : '720px'"
             :before-close="close">
    <el-form ref="form"
             :model="form"
             v-loading="loading"
             label-width="80px"
             class="recharge-form">
      <template v-if="gradeOrigin === 3">
        <el-form-item label="充值条数"
                      prop="count"
                      :rules="[{required: true, message: '请输入充值条数'}]">
          <el-input v-model="form.count"
                    size="small"
                    placeholder="请输入充值条数"></el-input>
        </el-form-item>
        <el-form-item label="充值金额"
                      prop="money"
                      :rules="[{required: true, message: '请输入充值金额'}]">
          <el-input v-model="form.money"
                    size="small"
                    placeholder="请输入充值金额"></el-input>
        </el-form-item>
      </template>
      <template v-else-if="waitingForPay">
        <el-form-item label-width="0px">
          <div style="display: flex; flex-direction: column; justify-content: center; align-items: center">
            <el-image style="width: 280px; height: 280px" :src="payImg"/>
            <div style="margin-top: 22px">
              <el-button size="small" @click="dialogVisible = false">取消支付</el-button>
              <el-button size="small" type="primary" @click="finishPay">已完成支付</el-button>
            </div>
          </div>

        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label=""
                      prop="template_id"
                      label-width="0px"
                      :rules="[{required: true, message: '请选择充值套餐', trigger: 'change'}]">
          <div class="recharge-templates">
            <div v-for="item in templateList"
                 :key="item.id"
                 class="recharge-template">
              <div class="template-container"
                   :class="{selected: form.template_id === item.id}"
                   @click="selectTemplate(item)">
                <p class="money">¥{{ item.money }}</p>
                <p class="detail">
                  <span class="price">¥{{ item.price }}元/条</span>
                  <span class="count">{{ item.count }}条</span>
                </p>
              </div>
            </div>
          </div>
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small"
                 @click="dialogVisible = false">
        取 消
      </el-button>
      <el-button size="small"
                 type="primary"
                 :loading="submitLoading"
                 @click="ensure">确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {mapGetters} from 'vuex'
import {getRechargeTemplates} from "@/plugins/api";

export default {
  name: "recharge",
  props: {
    agents: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      submitLoading: false,
      form: {
        sign: '',
        template_id: ''
      },
      templateList: [],
      loading: false,
      activeAgent: {},
      waitingForPay: false,
      payImg: ''
    }
  },
  computed: {
    ...mapGetters([
      'gradeOrigin'
    ]),
    title() {
      const activeAgent = this.activeAgent
      if (!activeAgent.sign) return '短信充值'
      return `正在为 ${activeAgent.company} 进行短信充值`
    },
    isAdmin() {
      return this.gradeOrigin === 3
    }
  },
  mounted() {
    // this.open()
  },
  methods: {
    async open(sign) {
      this.dialogVisible = true
      this.form.sign = sign
      this.payImg = ''
      this.waitingForPay = false
      let activeAgent = {}
      const agents = this.agents
      if (sign !== undefined) {
        agents.forEach(item => {
          if (item.sign === sign) {
            activeAgent = item
          }
        })
      }
      this.activeAgent = activeAgent
      let templateList = []
      this.$refs.form && this.$refs.form.clearValidate()
      if (!this.isAdmin) {
        this.loading = true
        let {data} = await getRechargeTemplates()
        this.loading = false
        templateList = data
      }
      this.templateList = templateList
    },
    close() {
      this.form.template_id = ''
      this.form.sign = ''
      this.form.money = ''
      this.form.count = ''
      this.dialogVisible = false
    },
    selectTemplate(item) {
      if (this.form.template_id === item.id) {
        this.form.template_id = ''
      } else {
        this.form.template_id = item.id
        this.$refs.form.validateField('template_id')
      }
    },
    ensure() {
      this.$refs.form.validate(async valid => {
        if (!valid) return false
        const {template_id, sign, count, money} = this.form
        const isAdmin = this.isAdmin
        let url,
            params
        if (isAdmin) {
          url = '/api/v1/sms/recharge/manager'
          params = {
            sign,
            count,
            money
          }
        } else {
          url = '/api/v1/sms/recharge/agent'
          params = {
            template_id
          }
        }
        this.submitLoading = true
        await this.$axios.post(url, params)
            .then((res) => {
              if (this.isAdmin) {
                this.$message.success('充值成功')
                this.finishPay()
              } else {
                this.waitingForPay = true
                this.payImg = res.url
              }
            }).catch(err => {
              this.$message.error(err.message)
            })
        this.submitLoading = false
      })
    },
    finishPay() {
      this.dialogVisible = false
      this.$emit('success', 1)
    }
  }
}
</script>

<style lang="less">
.recharge-form {
  min-height: 150px;

  .recharge-templates {
    display: flex;
    flex-wrap: wrap;
    margin-left: -24px;
    margin-top: -24px;
    padding: 20px;
    //width: 564px;

    .recharge-template {
      width: 25%;
    }

    .template-container {
      border: 1px solid #e2e2e2;
      padding: 12px;
      margin-left: 24px;
      margin-top: 24px;
      border-radius: 4px;
      cursor: pointer;

      &.selected {
        background: #409EFF;
        color: #fff;
        border: 1px solid #409EFF;

        .money {
          color: #fff;
        }
      }

      &:hover {
        border: 1px solid #409EFF;
      }

      .money, .detail {
        margin: 0;
        padding: 0;
      }

      .money {
        font-size: 24px;
        color: #000;
        font-weight: bold;
        text-align: center;
      }

      .detail {
        font-size: 12px;
        display: flex;
        justify-content: space-between;
      }
    }
  }

}
</style>